import axios from "axios";
import LRU from "lru-cache";
import config from "../config";
import { getMajorList, getMajorTree } from "~/api/major";
import { getClass } from "~/api/class";
import { getUserInfo } from "~/api/account/user";
import { getSiteInfo, getConfigInfo } from "~/api/site";
import { getNotice, getFirends, getWxLoginVaild } from "~/api/index";
import { getBannerList } from "~/api/banner";
import { getCourse, getBuyRecord, getRtcInfo, getSignInCourseList } from "~/api/course";
import { getNavList } from "~/api/nav";
import { getOrder, getOrderList, getMyOrderList } from "~/api/order";
import { getBuyCourseComboList } from "~/api/course-combo";
import { getSignAgreementList } from "~/api/course-agreement";
import { getMemberInfo, getMember } from "~/api/member";
import { getAuthUserInfo } from "~/api/authentication";
import { getPaidList } from "~/api/v2-question-bank/order.js";
import { LightenDarkenColor } from "~/utils/commonfun";
import { sendPayMessage, sendApplyMessage } from "~/api/index";
import { Toast } from "vant";
const CACHED = new LRU();
const ttl = 10 * 60 * 1000; //缓存时间

var timer = null;
function debounce(fn, wait) {
  return !(function() {
    if (timer !== null) {
      clearTimeout(timer);
    }
    timer = setTimeout(fn, wait);
  })();
}

const getPropsValue = (key, source) => {
  let result = source
    .map(i => {
      if (i.dictionaryCode == key) {
        return i.dictionaryValue;
      }
    })
    .filter(i => i !== undefined);
  if (result.length > 0) {
    return result[0];
  } else {
    console.error("System might lost dictionary code of " + key);
    return "";
  }
};

export default {
  async nuxtServerInit({ dispatch }, context) {},
  async initUser({ dispatch, commit }) {
    if (this.state.token) {
      const { id } = this.state.user_info;
      getUserInfo(id).then(res => {
        if (res && res.data && res.data.code == 200) {
          if(res.data.data){
            // commit("UPDATE_USERINFO", res.data.data);
            commit("SET_USERINFO", res.data.data);
          } else {
            commit("SIGN_OUT");
          }
        }
      });
    }
  },
  async initWebInfo({ dispatch, commit }, context) {
    let result = await getSiteInfo({
      typeCode: "BASE_INFO"
    });
    if (result && result.data.code == 200) {
      const { data } = result.data;
      let obj = {
        SUB_LOGO: getPropsValue("SUB_LOGO", data),
        BOTTOM_NAV_LOGO: getPropsValue("BOTTOM_NAV_LOGO", data),
        FAVICON: getPropsValue("FAVICON", data),
        BOTTOM_QR_CODE: getPropsValue("BOTTOM_QR_CODE", data),
        COMPANY_LOGO: getPropsValue("COMPANY_LOGO", data),
        DOMAIN: getPropsValue("DOMAIN", data),
        SYSTEM_NAME: getPropsValue("SYSTEM_NAME", data),
        ICP: getPropsValue("ICP", data),
        POLICE_RECORD: getPropsValue("POLICE_RECORD", data),
        SEO_KEY_WORDS: getPropsValue("SEO_KEY_WORDS", data),
        SEO_ACCESSORY: getPropsValue("SEO_ACCESSORY", data),
        COMPANY_NAME: getPropsValue("COMPANY_NAME", data),
        MOBILE: getPropsValue("MOBILE", data),
        TEL: getPropsValue("TEL", data),
        FAX: getPropsValue("FAX", data),
        ZIP_CODE: getPropsValue("ZIP_CODE", data),
        EMAIL: getPropsValue("EMAIL", data),
        QQ: getPropsValue("QQ", data),
        ABOUT_US: getPropsValue("ABOUT_US", data),
        SEO_DESCRIPTION: getPropsValue("SEO_DESCRIPTION", data),
        REGISTER_PROTOCOL: getPropsValue("REGISTER_PROTOCOL", data),
        PRIVACY_POLICY: getPropsValue("PRIVACY_POLICY", data),
        THEME_COLOR: getPropsValue("THEME_COLOR", data),
        ADVERTISEMENT_SWITCH: getPropsValue("ADVERTISEMENT_SWITCH", data),
        DISTRIBUTE_SWITCH: getPropsValue("DISTRIBUTE_SWITCH", data),
        VERIFY_TYPE: getPropsValue("VERIFY_TYPE", data),
        MEMBER_PROTOCOL: getPropsValue("MEMBER_PROTOCOL", data),
        THEME_TYPE: getPropsValue("THEME_TYPE", data),
        THEME_SETTING_OBJ: getPropsValue("THEME_SETTING_OBJ", data),
        VIDEO_BULLET: getPropsValue("VIDEO_BULLET", data),
        BACKEN_HOST: getPropsValue("BACKEN_HOST", data),
        ANDROID_APP_URL: getPropsValue("ANDROID_APP_URL", data),
        IOS_APP_URL: getPropsValue("IOS_APP_URL", data),
      };

      //格式化字典值
      Object.keys(obj).forEach((i, x) => {
        if (obj[i] == "") {
          delete obj[i];
        }
      });

      //设置跟主题色相近的颜色
      if (obj.hasOwnProperty("THEME_COLOR")) {
        let THEME_COLOR_LIGHTER = LightenDarkenColor(obj.THEME_COLOR, 40);
        let SET_THEME_COLOR_DARKER = LightenDarkenColor(obj.THEME_COLOR, -40);
        commit("SET_THEME_COLOR_LIGHTER", THEME_COLOR_LIGHTER);
        commit("SET_THEME_COLOR_DARKER", SET_THEME_COLOR_DARKER);
      }

      commit("UPDATE_WEB_INFO", obj);
      //执行seo附属代码
      if (obj.hasOwnProperty("SEO_ACCESSORY")) {
        eval(obj.SEO_ACCESSORY);
      }
    }
    let result1 = await getSiteInfo({
      typeCode: "SYS"
    });
    if (result1 && result1.data.code == 200) {
      const { data } = result1.data;
      let RICHTEXT_SWITCH = getPropsValue("RICHTEXT_SWITCH", data);
      let AGENT_AREA_SWITCH = getPropsValue("AGENT_AREA_SWITCH", data);
      let AGENT_TEAM_SWITCH = getPropsValue("AGENT_TEAM_SWITCH", data);

      let obj = {
        RICHTEXT_SWITCH,
        AGENT_AREA_SWITCH,
        AGENT_TEAM_SWITCH
      };
      //格式化字典值
      Object.keys(obj).forEach((i, x) => {
        if (obj[i] == "") {
          delete obj[i];
        }
      });

      commit("UPDATE_WEB_INFO", obj);

      let CLIENT_I18N_SWITCH = getPropsValue("CLIENT_I18N_SWITCH", data);
      let CLIENT_I18N = getPropsValue("CLIENT_I18N", data);
      if (CLIENT_I18N) {
        commit("SET_LANG", CLIENT_I18N);
      }
      if (CLIENT_I18N_SWITCH) {
        commit("SET_IS_CLIENT_LOCALE", CLIENT_I18N_SWITCH);
      }
    }

    let result2 = await getConfigInfo();
    if (result2 && result2.data.code == 200) {
      const { rows } = result2.data.data;
      let KLFX = getPropsValue("KLFX", rows);
      let KLHY = getPropsValue("KLHY", rows);
      let KLGJH = getPropsValue("KLGJH", rows);
      let KLSTFWB = getPropsValue("KLSTFWB", rows);
      let KLXBK = getPropsValue("KLXBK", rows);
      let KLST = getPropsValue("KLST", rows);
      let KLGL = getPropsValue("KLGL", rows);
      let KLQYDL = getPropsValue("KLQYDL", rows);
      let KLTDFX = getPropsValue("KLTDFX", rows);
      let KLXXDJ = getPropsValue("KLXXDJ", rows);
      let KLKCTC = getPropsValue("KLKCTC", rows);
      let KLDX = getPropsValue("KLDX", rows);
      let KLSMRZ = getPropsValue("KLSMRZ", rows);
      let KLYHJ = getPropsValue("KLYHJ", rows);
      let KLPT = getPropsValue("KLPT", rows);
      let KLYJDL = getPropsValue("KLYJDL", rows);
      let KLHWSC = getPropsValue("KLHWSC", rows);
      let KLXBTK = getPropsValue("KLXBTK", rows);
      let KLDLTK = getPropsValue("KLDLTK", rows);
      let KLWXMSG = getPropsValue("KLWXMSG", rows);
      let KLJBTK = getPropsValue("KLJBTK", rows);
      let KLCGBG = getPropsValue("KLCGBG", rows);
      let KLZTQH = getPropsValue("KLZTQH", rows);
      let KLKJZF = getPropsValue("KLKJZF", rows);
      let KLQXFL = getPropsValue("KLQXFL", rows);
      let KLKCXY = getPropsValue("KLKCXY", rows);
      let KLZSCL = getPropsValue("KLZSCL", rows);
      let KLJSRZ = getPropsValue("KLJSRZ", rows);
      let KLZDYBD = getPropsValue("KLZDYBD", rows);
      let KLZYGL = getPropsValue("KLZYGL", rows);
      let KLKCQD = getPropsValue("KLKCQD", rows);
      let KLYXK = getPropsValue("KLYXK", rows);
      let KLKCKT = getPropsValue("KLKCKT", rows);
      let KLAPP = getPropsValue("KLAPP", rows);
      let KLKCPJ = getPropsValue("KLKCPJ", rows);
      let KLYXRZ = getPropsValue("KLYXRZ", rows);
      let obj = {
        KLFX,
        KLHY,
        KLGJH,
        KLSTFWB,
        KLXBK,
        KLST,
        KLGL,
        KLQYDL,
        KLTDFX,
        KLXXDJ,
        KLKCTC,
        KLDX,
        KLSMRZ,
        KLYHJ,
        KLPT,
        KLYJDL,
        KLHWSC,
        KLXBTK,
        KLDLTK,
        KLWXMSG,
        KLJBTK,
        KLCGBG,
        KLZTQH,
        KLKJZF,
        KLQXFL,
        KLKCXY,
        KLZSCL,
        KLJSRZ,
        KLZDYBD,
        KLZYGL,
        KLKCQD,
        KLYXK,
        KLKCKT,
        KLAPP,
        KLKCPJ,
        KLYXRZ,
      };
      //格式化字典值
      Object.keys(obj).forEach((i, x) => {
        if (obj[i] == "") {
          delete obj[i];
        }
      });
      commit("SETMD", obj);
      if (KLXBTK == 1) {
        this.dispatch("getMineV2QuestionBankList");
      }
      if (KLDLTK == 1) {
        if (process.client) {
          window.$nuxt.$store.commit("SET_IS_LOADING", true);
        }
        commit("SET_V2QUESTION_ROUTER");
      }
    }
  },
  async initMajorList({ dispatch, commit }, context) {
    const { major_list } = this.state;
    if (major_list && major_list.length == 0) {
      let result = await getMajorList({ sort: "id", sortType: "desc" });
      if (result && result.data.code == 200) {
        commit("SET_MAJOR_LIST", result.data.data.rows);
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async initMajorTree({ dispatch, commit }, context) {
    const { major_tree } = this.state;
    if (major_tree && major_tree.length == 0) {
      let result = await getMajorTree({ sort: "id", sortType: "desc" });
      if (result && result.data.code == 200) {
        commit("SET_MAJOR_TREE", result.data.data);
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async initClassList({ dispatch, commit }, context) {
    const { class_list } = this.state;
    if (class_list && class_list.length == 0) {
      let result = await getClass({ sort: "id", sortType: "desc" });
      if (result && result.data.code == 200) {
        commit("SET_CLASS_LIST", result.data.data.rows);
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async initNoticeList({ dispatch, commit }, context) {
    const { notice_list } = this.state;
    if (notice_list && notice_list.length == 0) {
      let result = await getNotice({
        sort: "id",
        sortType: "desc",
        offset: 0,
        limit: 10,
        type: 1,
        isOpen: 1
      });
      if (result && result.data.code == 200) {
        commit("SET_NOTICE_LIST", result.data.data.rows);
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async initBannerList({ dispatch, commit }, context) {
    const { banner_list } = this.state;
    if (banner_list && banner_list.length == 0) {
      let result = await getBannerList({ sort: "id", sortType: "desc",isUse:1 });
      if (result && result.data.code == 200) {
        commit("SET_BANNER_LIST", result.data.data.rows);
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async initCourseList({ dispatch, commit }, context) {
    const { course_list } = this.state;
    if (course_list && course_list.length == 0) {
      let result = await getCourse({ sort: "id", sortType: "desc" });
      if (result && result.data.code == 200) {
        commit("SET_COURSE_LIST", result.data.data.rows);
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async initBuyRecord({ commit }) {
    const { buy_record_list, user_info, token } = this.state;
    // console.log("buy_record_list:", buy_record_list);
    let is_login = token && Object.keys(user_info).length > 0;
    // console.log("is_login:", is_login);
    if (is_login) {
      // if (buy_record_list && buy_record_list.length == 0) {
      //   let result = await getOrder({
      //     userId: user_info.id
      //   });
      //   if (result && result.data.code == 200) {
      //     commit("SET_BUYRECORD_LIST", result.data.data.rows || []);
      //   } else {
      //     commit("SET_IS_LOADING", false);
      //   }
      // }
      let result = await getOrder({
        userId: user_info.id
      });
      if (result && result.data.code == 200) {
        commit("SET_BUYRECORD_LIST", result.data.data.rows || []);
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  //初始化购买套餐
  async initBuyCombo({ commit }) {
    const { buy_combo_list, user_info, token } = this.state;
    // console.log("buy_combo_list:", buy_combo_list);
    let is_login = token && Object.keys(user_info).length > 0;
    // console.log("is_login:", is_login);
    if (is_login) {
      if (buy_combo_list && buy_combo_list.length == 0) {
        let result = await getBuyCourseComboList({
          userId: user_info.id
        });
        if (result && result.data.code == 200) {
          commit("SET_BUYCOMBO_LIST", result.data.data.rows || []);
        } else {
          commit("SET_IS_LOADING", false);
        }
      }
    }
  },
  //初始化签署课程协议
  async initSignAgreement({ commit }) {
    const { sign_Agreement_list, user_info, token } = this.state;
    // console.log("sign_Agreement_list:", sign_Agreement_list);
    let is_login = token && Object.keys(user_info).length > 0;
    // console.log("is_login:", is_login);
    if (is_login) {
      if (sign_Agreement_list && sign_Agreement_list.length == 0) {
        let result = await getSignAgreementList(user_info.id);
        if (result && result.data.code == 200) {
          commit("SET_SIGN_AGREEMENT_LIST", result.data.data || []);
        } else {
          commit("SET_IS_LOADING", false);
        }
      }
    }
  },
  //初始化当天课程签到列表
  async initSignInCourse({ commit }) {
    const { sign_in_course_list, user_info, token } = this.state;
    // console.log("sign_in_course_list:", sign_in_course_list);
    let is_login = token && Object.keys(user_info).length > 0;
    // console.log("is_login:", is_login);
    if (is_login) {
      if (sign_in_course_list && sign_in_course_list.length == 0) {
        let result = await getSignInCourseList(user_info.id);
        if (result && result.data.code == 200) {
          commit("SET_SIGN_IN_COURSE_LIST", result.data.data || []);
        } else {
          commit("SET_IS_LOADING", false);
        }
      }
    }
  },
  async initMember({ commit }) {
    const { user_info, token } = this.state;
    let is_login = token && Object.keys(user_info).length > 0;
    if (is_login) {
      let memberDiscount = await getMemberInfo(user_info.id);
      let member = await getMember(user_info.id);
      if (
        memberDiscount &&
        memberDiscount.data.code == 200 &&
        member &&
        member.data.code == 200
      ) {
        commit("SET_MEMBER_DISCOUNT", memberDiscount.data.data || {});
        commit("SET_MEMBER_INFO", member.data.data || {});
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async initAuthentication({ commit }) {
    const { user_info, token } = this.state;
    let is_login = token && Object.keys(user_info).length > 0;
    if (is_login) {
      let result = await getAuthUserInfo(user_info.id);
      if (result && result.data && result.data.code == 200) {
        let obj = result.data.data;
        let authentication = {
          departmentId: null,
          hospitalId: null,
          identityId: null,
          professionalId: null
        };
        if (obj) {
          commit("SET_AUTHENTICATION", obj || authentication);
        }
      } else {
        // this.$toast("网络波动，请稍后再试！");
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async initBuyCourseRecord({ commit }) {
    const { course_record_list, user_info, token } = this.state;
    let is_login = token && Object.keys(user_info).length > 0;
    if (is_login) {
      // if (course_record_list && course_record_list.length == 0) {
      //   let result = await getOrderList({
      //     userId: user_info.id
      //   });
      //   if (result && result.data.code == 200) {
      //     commit("SET_COURSE_RECORD_LIST", result.data.data || []);
      //   } else {
      //     commit("SET_IS_LOADING", false);
      //   }
      // }
      let result = await getOrderList({
        userId: user_info.id
      });
      if (result && result.data.code == 200) {
        commit("SET_COURSE_RECORD_LIST", result.data.data || []);
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async initMyBuyCourseRecord({ commit }) {
    const { course_record_list, user_info, token } = this.state;
    let is_login = token && Object.keys(user_info).length > 0;
    if (is_login) {
      if (course_record_list && course_record_list.length == 0) {
        let result = await getMyOrderList({
          userId: user_info.id
        });
        if (result && result.data.code == 200) {
          commit("SET_COURSE_RECORD_LIST", result.data.data.rows || []);
        } else {
          commit("SET_IS_LOADING", false);
        }
      }
    }
  },
  async initNavList({ commit }) {
    const { nav_list } = this.state;
    if (nav_list && nav_list.length == 0) {
      let result = await getNavList({ sort: "sort_index desc" });
      if (result && result.data.code == 200) {
        commit("SET_NAV_list", result.data.data || []);
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async initFriendsList({ commit }) {
    const { friend_links_list } = this.state;
    if (friend_links_list && friend_links_list.length == 0) {
      let result = await getFirends({ sort: "id", sortType: "desc" });
      if (result && result.data.code == 200) {
        commit("SET_FIREND_LINK_LIST", result.data.data.rows || []);
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async getWxValid({ commit }) {
    let result = await getWxLoginVaild();
    if (result && result.data.code == 200) {
      commit(
        "SET_THIRD_PART_INFO",
        result.data.data || {
          mp: false,
          open: false,
          qq: false
        }
      );
    } else {
      commit("SET_IS_LOADING", false);
    }
  },
  async initRtcInfo({ dispatch, commit }, context) {
    const { user_info, token } = this.state;
    let is_login = token && Object.keys(user_info).length > 0;
    if (is_login) {
      let result = await getRtcInfo();
      if (result && result.data.code == 200) {
        const { rows } = result.data.data;
        if (rows.length > 0) {
          commit("SET_RTC_INFO", rows[0]);
        }
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  /* 用户购买的题库 */
  async getMineV2QuestionBankList({ dispatch, commit }, context) {
    const { user_info, token } = this.state;
    let is_login = token && Object.keys(user_info).length > 0;
    if (is_login) {
      let result = await getPaidList({
        userId: user_info.id,
        sort: 'id desc',
      });
      if (result && result.data.code == 200) {
        const { data } = result.data;
        if (data && data.length > 0) {
          let questionList = data.map(item=>{
            return {
              ...item,
              deleted:new Date().getTime() > item.endTime ? 1 : 0
            }
          })
          commit("SET_QUESTION_LIST", questionList);
        }
      } else {
        commit("SET_IS_LOADING", false);
      }
    }
  },
  async setLoadingAsync({ commit }, context) {
    debounce(() => {
      setTimeout(() => {
        commit("SET_IS_LOADING", false);
      }, 3000);
    }, 1000);
  },
  /* 检查微信状态 未绑定指引绑定 */
  async checkBingWechatStatus({ commit }, context) {
    const { user_info, token, kl_md } = this.state;
    const { params, type } = context.payload;
    console.log("发送微信消息=>", params, type);
    if (kl_md.KLWXMSG != 1) {
      return;
    }
    /* 未绑定微信 不允许发送微信消息 */
    if (!(user_info.wechatId && user_info.wechatId.replace(/(\s*$)/g, ""))) {
      if (process.client) {
        window.$nuxt.$dialog
          .confirm({
            title: "提示",
            message: "您还未绑定微信，将无法通过微信给你发送系统消息哦~",
            showCancelButton: true,
            confirmButtonText: "去绑定",
            cancelButtonText: "下次再说"
          })
          .then(() => {
            window.$nuxt.$router.push("/m/setting");
          })
          .catch(() => {
            // on cancel
          });
      }
      
    } else {
      if (type == "pay") {
        let result = await sendPayMessage(params);
        if (result && result.data && result.data.code == 200) {
        }
      } else if (type == "apply") {
        let result = await sendApplyMessage(params);
        if (result && result.data && result.data.code == 200) {
        }
      }
    }
  }
};
